/**
 * Created by Administrator on 2017/2/6.
 */

var replay = require('../../../logic/cache/replay.js');
var roomManager = require('../../../logic/world/roomManager');

module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};

var handler = Handler.prototype;

handler.get = function (msg, session, next) {
    msg.nolog = true;
    var self = this;
    var uid = session.uid;

    gPlayerManger.getPlayer(uid, function (player) {
        if (!player) {
            next(null, {code: Code.UID_INVALID});
            return;
        }

        replay.getReports(player.getReports(), function (err, reports) {
            if (err) {
                next(null, {code: Code.CACHE_ERROR});
                return;
            }

            next(null, {reports: reports});
        });
    });
};

handler.getOfAgency = function (msg, session, next) {
    var uid = session.uid;
    var gameType = msg.gameType;
    var rooms = [];
    DB.createrooms.find({"creator": uid, "type": 1}).toArray(function (err, items) {
        if (err) {
            logger.error("db err = %j", err.stack);
        }
        rooms = items;
        var rids = [];
        if (rooms.length > 0) {
            rooms.forEach(function (item) {
                rids.push(item._id);
            });
            rids.reverse();
        } else {
            next(null, {code: Code.ROOM_INVALID});
        }
        replay.getReports(rids, function (err, reports) {
            if (err) {
                next(null, {code: Code.CACHE_ERROR});
                return;
            }

            var result = reports.filter(function (arg) {
                return arg.gameType == gameType;
            });
            if (result == null) {
                next(null, {reports: [], "agency": true});
            } else {
                next(null, {reports: result, "agency": true});
            }
        });
    });

}